import { MyVue } from 'src/wl/my_vue';
import Vue from 'vue';
import { Component, Emit, Prop, Provide, Watch } from 'vue-property-decorator';
import { WebManageConst } from "src/consts/web_manage_const";
import { updateSelection } from 'src/utils/list_utils';
import { fetchList } from 'src/api/article'
import Sortable from 'sortablejs'

@Component({})
export default class WebManagePanel extends MyVue {
    name: string = 'WebManagePanel';
    formData: any;
    footerFlag: boolean = true;
    applyShow: boolean;
    title: String;
    titleIcon: String;
    feature_code: String;
    isNoOther: Boolean;
    selection: any[];
    selectId: Number | String
    isUp: Boolean;
    isDown: Boolean;
    isEdit: Boolean;
    isNoChange: Boolean;

    initData(that?: any): void {

        that.formData = WLStore().state.webMShow;
        that.feature_code = Config.featureCode2 + 'web.model.WebsiteView'
        that.selection = [];
        that.isNoChange = true
        that.isNoOther = true
        that.applyShow = false
        that.isUp = true
        that.isDown = true
        that.selectId = null
        if (WLStore().state.webManage.type == "edit") {
            that.isEdit = true
            if (that.formData.login_key == "web") {
                that.isNoOther = false
            } else {
                that.isNoOther = true
            }

            var user = getUserInfo()
            for (let i = 0; i < user.roles.length; i++) {
                if (user.roles[i].id == 1) {
                    that.applyShow = true
                }
            }

            if (!that.formData.account) {
                that.formData.account = {}
                that.formData.account.name = getUserInfo().account
                that.formData.account.id = getUserInfo().userId
                that.formData.account.create_time = new Date().getTime()
            }

            var caList = that.formData[that.formData.login_type + 'CaMsgs']
            if (isNoEmpty(caList)) {
                for (let k = 0; k < caList.length; k++) {
                    if (!that.applyShow) {
                        that.formData[that.formData.login_type + 'CaMsgs'][k].uown_name = user.account
                    }
                }
            }

            that.title = "网站信息详情"
            that.titleIcon = "btn_xq"
        } else if (WLStore().state.webManage.type == "add") {
            that.isEdit = false
            that.title = "新增网站信息"
            that.titleIcon = "pop_xz"
            that.formData.login_type = "account"
            that.formData.login_key = that.formData.login_type
            that.formData.account = {}
            that.formData.account.name = getUserInfo().account
            that.formData.account.id = getUserInfo().userId
            that.formData.account.create_time = new Date().getTime()
        }

        var configList = that.formData[that.formData.login_key + 'Configs']
        if (isNoEmpty(configList)) {
            for (let j = 0; j < configList.length; j++) {
                configList[j].ind = j
            }
        }
    }

    get _config(): string {
        return this.formData[this.formData.login_key + 'Configs']
    }

    @Watch('_config', { immediate: true })
    onConfigChanged(val: any) {
        var flag = true
        var objOld = this.formData.oldConfigs

        if (isNoEmpty(objOld)) {
            if (objOld.length == val.length) {
                for (let i = 0; i < objOld.length; i++) {
                    for (const key in objOld[i]) {
                        if (val[i][key] != objOld[i][key]) {
                            flag = false
                        }
                    }
                }
            } else {
                flag = false
            }
        }

        if (this.isNoChange) {
            this.isNoChange = flag
        }
    }


    get _acc(): string {
        return this.formData[this.formData.login_key + 'Accounts']
    }

    @Watch('_acc', { immediate: true })
    onAccChanged(val: any) {
        var flag = true
        var objOld = this.formData.oldAccounts

        if (isNoEmpty(objOld)) {
            if (objOld.length == val.length) {
                for (let i = 0; i < objOld.length; i++) {
                    for (const key in objOld[i]) {
                        if (val[i][key] != objOld[i][key]) {
                            flag = false
                        }
                    }
                }
            } else {
                flag = false
            }
        }

        if (this.isNoChange) {
            this.isNoChange = flag
        }
    }

    get _ca(): string {
        return this.formData[this.formData.login_key + 'CaMsgs']
    }

    @Watch('_ca', { immediate: true })
    onCaChanged(val: any) {
        var flag = true
        var objOld = this.formData.oldCaMsgs

        if (isNoEmpty(objOld)) {
            if (objOld.length == val.length) {
                for (let i = 0; i < objOld.length; i++) {
                    for (const key in objOld[i]) {
                        if (val[i][key] != objOld[i][key]) {
                            flag = false
                        }
                    }
                }
            } else {
                flag = false
            }
        }

        if (this.isNoChange) {
            this.isNoChange = flag
        }
    }


    get _url(): string {
        return this.formData.url
    }

    @Watch('_url', { immediate: true })
    onUrlChanged(val: any) {
        var objOld = this.formData.oldUrl
        if (objOld != val) {
            this.isNoChange = false
        }
    }

    alretErr(): void {
        WLMessage("网站信息有改变,请保存后再检测", "warning");
    }

    // created() {
    //     this.setSort()
    // }

    // setSort() {
    //     const el = document.querySelectorAll('.el-table__body-wrapper > table > tbody')[3]
    //     this.sortable = Sortable.create(el, {
    //         ghostClass: 'sortable-ghost', 
    //         setData: function (dataTransfer) {
    //             dataTransfer.setData('Text', '')
    //         },
    //         onEnd: evt => {
    //             const targetRow = this.formData[this.formData.login_key + 'Configs'].splice(evt.oldIndex, 1)[0]
    //             this.formData[this.formData.login_key + 'Configs'].splice(evt.newIndex, 0, targetRow)
    //         }
    //     })
    // }

    handleSelectionChange(selection: any): void {
        this.handleBtnShow(selection)
        if (selection[0]) {
            this.selectId = selection[0].ind
        }
    }

    handleBtnShow(data: any): void {
        var configList = this.formData[this.formData.login_key + 'Configs']
        if (data.length == 1 && configList.length > 1) {
            this.isUp = false
            this.isDown = false
        } else {
            this.isUp = true
            this.isDown = true
        }
    }


    editWebM(): void {
        this.$refs.webMForm.validate((valid: Boolean) => {
            if (valid) {
                var sendData = this.formData
                var type = WLStore().state.webMShow.login_key


                var patt = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?/;
                if (!patt.test(sendData.url)) {
                    WLMessage("网址格式不正确，请修改", "warning")
                    return
                }
                if (type == "account") {
                    if (!isNoEmpty(sendData.accountAccounts)) {
                        WLMessage("公共账号信息为空，请补充完成", "warning")
                        return
                    }
                } else if (type == "ca") {
                    if (!isNoEmpty(sendData.caCaMsgs)) {
                        WLMessage("ca证书信息为空，请补充完成", "warning")
                        return
                    }
                } else if (type == "caAndAccount") {
                    if (!isNoEmpty(sendData.caAndAccountAccounts)) {
                        WLMessage("公共账号信息为空，请补充完成", "warning")
                        return
                    }

                    if (!isNoEmpty(sendData.caAndAccountCaMsgs)) {
                        WLMessage("ca证书信息为空，请补充完成", "warning")
                        return
                    }
                }


                var list = WLStore().state.webMShow[type + 'Accounts']
                var k = 0
                if (isNoEmpty(list)) {
                    for (let i = 0; i < list.length; i++) {
                        if (list[i].flag) {
                            k += 1
                            if (k > 1) {
                                WLMessage("默认登录账号只能有一个", "warning")
                                return
                            }
                        }
                    }
                }
                switch (type) {
                    case "caAndAccount":
                        sendData.webAccounts = sendData.caAndAccountAccounts
                        sendData.webConfigs = sendData.caAndAccountConfigs
                        sendData.webCaMsgs = sendData.caAndAccountCaMsgs
                        break;
                    case "account":
                        sendData.webAccounts = sendData.accountAccounts
                        sendData.webConfigs = sendData.accountConfigs
                        sendData.webCaMsgs = []
                        break;
                    case "ca":
                        sendData.webCaMsgs = sendData.caCaMsgs
                        sendData.webConfigs = sendData.caConfigs
                        sendData.webAccounts = []
                        break;
                }

                // delete sendData.caAndAccountAccounts
                // delete sendData.caAndAccountConfigs
                // delete sendData.caAndAccountCaMsgs
                // delete sendData.accountAccounts
                // delete sendData.accountConfigs
                // delete sendData.caCaMsgs
                // delete sendData.caConfigs

                var configList = WLStore().state.webMShow[type + 'Configs']
                var configFlag = true
                if (isNoEmpty(configList)) {
                    for (let j = 0; j < configList.length; j++) {
                        if (configList[j].index_id) {
                            configFlag = false
                        }
                    }
                }

                if (configFlag) {
                    this.$confirm('配置项未修改是否确认添加?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        if (WLStore().state.webManage.type == "edit") {
                            WLDispatch(WebManageConst.DispatchWebMEdit, sendData);
                        } else if (WLStore().state.webManage.type == "add") {
                            WLDispatch(WebManageConst.DispatchWebMAdd, sendData);
                        }
                    }).catch(() => { })
                } else {
                    if (WLStore().state.webManage.type == "edit") {
                        WLDispatch(WebManageConst.DispatchWebMEdit, sendData);
                    } else if (WLStore().state.webManage.type == "add") {
                        WLDispatch(WebManageConst.DispatchWebMAdd, sendData);
                    }
                }

            } else {
                WLMessage("必填字段为空,无法编辑网站信息", "warning")
                return false;
            }
        })
    }

    configRowDelete(index: Number, data: any): void {
        var configType = getValueByKey("web_config_type", data.config_type)
        this.$confirm(`是否删除配置项：${configType}?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            var type = WLStore().state.webMShow.login_type
            this.formData[type + 'Configs'].splice(index, 1);
        }).catch(() => { })
    }


    configRowEdit(index: Number, data: any): void {
        var sendData: any = {}
        sendData.config_type = "edit"
        sendData.config_index = index;
        WLCommit(WebManageConst.CommitConfig, sendData)
    }

    loginChange(val: String): void {
        this.selectId = ""
        WLCommit(WebManageConst.CommitWebMLogin, val)
        var configList = this.formData[this.formData.login_key + 'Configs']
        if (isNoEmpty(configList)) {
            for (let j = 0; j < configList.length; j++) {
                configList[j].ind = j
            }
        }

        var typeOld = this.formData.oldLoginType
        if (this.isNoChange) {
            this.isNoChange = val == this.formData.oldLoginType
        }
        cd("typeOld", typeOld)
    }

    doConfigNew(): void {
        var sendData: any = {}
        sendData.config_type = "add"
        sendData.config_index = "";
        WLCommit(WebManageConst.CommitConfig, sendData)
    }

    configRowUp(): void {
        var index = 0
        var list = this.formData[this.formData.login_key + 'Configs']
        for (let i = 0; i < list.length; i++) {
            if (list[i].ind == this.selectId) {
                index = i
                break
            }
        }
        if (index > 0) {
            var sendData: any = {}
            sendData.config_type = "up"
            sendData.config_index = index
            WLCommit(WebManageConst.CommitConfig, sendData)
            WLCommit(WebManageConst.CommitConfigData, "")
        }
    }

    configRowDown(): void {
        var index = 0
        var list = this.formData[this.formData.login_key + 'Configs']
        for (let i = 0; i < list.length; i++) {
            if (this.selectId == list[i].ind) {
                index = i
                break
            }
        }

        if (index < list.length - 1) {
            var sendData: any = {}
            sendData.config_type = "down"
            sendData.config_index = index
            WLCommit(WebManageConst.CommitConfig, sendData)
            WLCommit(WebManageConst.CommitConfigData, "")
        }
    }

    doConfigReSet(): void {
        this.$confirm(`确定清空所有配置项?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            var type = WLStore().state.webMShow.login_type
            this.formData[type + 'Configs'].splice(0, this.formData[type + 'Configs'].length)
        }).catch(() => { })
    }

    accountsRowEdit(index: Number, data: any): void {
        var sendData: any = {}
        sendData.acc_type = "edit"
        sendData.acc_index = index;
        WLCommit(WebManageConst.CommitAcc, sendData)
    }

    accountsRowDelete(index: Number, data: any): void {
        this.$confirm(`是否删除账号：${data.account}?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            var type = WLStore().state.webMShow.login_type
            this.formData[type + 'Accounts'].splice(index, 1);
        }).catch(() => { })
    }

    doAccNew(): void {
        var sendData: any = {}
        sendData.acc_type = "add"
        sendData.acc_index = "";
        WLCommit(WebManageConst.CommitAcc, sendData)
    }

    doAccountsReSet(): void {
        this.$confirm(`确定清空所有账号?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            var type = WLStore().state.webMShow.login_type
            this.formData[type + 'Accounts'].splice(0, this.formData[type + 'Accounts'].length)
        }).catch(() => { })
    }

    caRowDelete(index: Number, data: any): void {
        this.$confirm(`是否删除ca证书：${data.pin}?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            var type = WLStore().state.webMShow.login_type
            this.formData[type + 'CaMsgs'].splice(index, 1);
        }).catch(() => { })
    }

    caRowEdit(index: Number, data: any): void {
        var sendData: any = {}
        sendData.ca_type = "edit"
        sendData.ca_index = index;
        WLCommit(WebManageConst.CommitCa, sendData)
    }

    doCaNew(): void {
        var type = WLStore().state.webMShow.login_type

        if (WLStore().state.webMShow[type + 'CaMsgs'] && WLStore().state.webMShow[type + 'CaMsgs'].length > 0) {
            WLMessage("已存在ca证书，编辑原有证书或删除原有证书再新增", "warning")
            return
        }

        var sendData: any = {}
        sendData.ca_type = "add"
        sendData.ca_index = "";
        WLCommit(WebManageConst.CommitCa, sendData)
    }

    doCaReSet(): void {
        this.$confirm(`确定清空所有ca证书?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            var type = WLStore().state.webMShow.login_type
            this.formData[type + 'CaMsgs'].splice(0, this.formData[type + 'CaMsgs'].length)
        }).catch(() => { })
    }

    rowClassName(data: any): string {
        if (data.row.selected) {
            return 'selected_row';
        }

        return '';
    }
}